package com.example.bigwork.fragment;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.bigwork.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;


public class StoreFragment extends Fragment {

    private View recommendPage;

    private Button btnDown,btnDownUser;
    private ImageView img,imgUser;

    private Handler handler;

    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //绑定布局文件
        recommendPage = inflater.inflate(R.layout.store_tablayout_activity,null);

        //绑定控件
        getViews();



        //点击事件
        //下载网络图片
        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载图片
                downloadImg("https://img.wxcha.com/m00/90/a5/d1d167451213c94da52f7ddf31d8da3b.jpg");

            }
        });

        //加载本地图片
        btnDownUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK,null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                //intent 待启动的Intent 100（requestCode）请求码，返回时用来区分是那次请求
                startActivityForResult(intent ,100);
            }
        });


        //初始化handler
        handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                //判断msg
                switch (msg.what){
                    case 1:
                        //获取封装的数据
                        Bitmap bitmap = (Bitmap) msg.obj;
                        //将获取到的数据显示到图像控件中
                        img.setImageBitmap(bitmap);
                        break;

                }
            }
        };



        return recommendPage;



    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //返回成功，请求码（对应启动时的requestCode）
        if(resultCode == RESULT_OK && requestCode==100)
        {
            //方式二
            Uri uri = data.getData();
            ContentResolver cr = getContext().getContentResolver();
            try {
                //根据Uri获取流文件
                InputStream is = cr.openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize =3;
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
                imgUser.setImageBitmap(bitmap);
            }
            catch(Exception e)
            {
                Log.i("lyf", e.toString());
            }
        }
        super.onActivityResult(requestCode, resultCode, data);


    }

    private void getViews() {
        btnDown = recommendPage.findViewById(R.id.btn_down);
        img = recommendPage.findViewById(R.id.iv_img);
        btnDownUser = recommendPage.findViewById(R.id.btn_down_user);
        imgUser = recommendPage.findViewById(R.id.iv_img_user);
    }


    private void downloadImg(String imgUrl) {
        //启动子线程获取图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1.实例化URL对象
                    URL url = new URL(imgUrl);
                    //2.获取图片对应的网络输入流
                    InputStream in = url.openStream();
                    //3.利用Bitmap工厂将图片对应的输入流转成Bitmap对象
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    //4.获取Message对象，并封装数据
                    Message msg = handler.obtainMessage();
                    //封装bitmap
                    msg.obj = bitmap;
                    //标记一下当前的Message
                    msg.what = 1;
                    //5.通过handle引用将Message对象发布出去
                    handler.sendMessage(msg);


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();



    }





}